<template>
  <el-row>
    <el-col :span="4">
      <div style="height: 825px; overflow:auto">
        <el-tree ref="orgTreeDom" v-loading="tableLoading" :data="orgTree1" :props="orgTreeProps1"
                 node-key="organizationId" default-expand-all highlight-current :expand-on-click-node="false"
                 @current-change="changeOrgNode"></el-tree>
      </div>
    </el-col>
    <el-col :span="20">
      <div class="top-panel__box">
        <el-form :model="orgForm" ref="orgForm" inline size="small" onsubmit="return false">
          <el-form-item>
            <el-button type="primary" @click="addOrg" v-permission="'ORG_ADD'">
              <fa-icon class="fa-plus"/>
              新增渠道
            </el-button>
          </el-form-item>
          <el-form-item>
            <tooltip :tooltipOption="TOOLTIP_OPTION"/>
          </el-form-item>
        </el-form>
      </div>
      <el-row class="table-top">
        <el-table :data="dataList" v-loading="tableLoading" tooltip-effect="light" class="tc-table" size="small">
          <!-- <el-table-column type="index" width="55" fixed="left" label="序号"></el-table-column> -->
          <template v-for="(column, index) in HEAD_LIST">
            <el-table-column :prop="column.prop" :label="column.label" :key="index" :width="column.width"
                             :show-overflow-tooltip="true"/>
          </template>
          <el-table-column prop="operation" class-name="oper-col" label="操作" :width="350">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" plain @click="editRow(scope.row)" v-permission="'ORG_AUDIT'">编辑
              </el-button>
              <el-button size="mini" type="primary" plain @click="addChildRow(scope.row)" v-permission="'ORG_ADD_ORG'">
                添加子渠道
              </el-button>
              <el-button v-if="scope.row.organizationStatus === 'OPEN'" size="mini" type="info" plain
                         @click="closeOrg(scope.row)" v-permission="'ORG_STOP'">停用
              </el-button>
              <el-button v-if="scope.row.organizationStatus === 'CLOSE'" size="mini" type="success" plain
                         @click="openOrg(scope.row)" v-permission="'ORG_STOP'">启用
              </el-button>
              <el-button size="mini" type="danger" plain @click="deleteRow(scope.row)" v-permission="'ORG_DELETE'">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row class="pagination-top">
        <pagination :pageNum.sync="orgForm.pageNum" :curSizes.sync="orgForm.pageSize" :total="total"
                    @getList="getList"/>
      </el-row>
    </el-col>
    <!--新增渠道-->
    <el-dialog :title="dialogTitle" :visible.sync="dialog.orgDialog" width="34%" :close-on-click-modal="false">
      <AddOrEditOrg  v-if="dialog.orgDialog" :isEdit="this.dialogTitle==='添加子渠道'" :editData="editData" :org-tree="orgTree" @uppdataSuccess="updataData"
                       @close="closeEditOrg"/>
    </el-dialog>
  </el-row>

</template>

<script>
import {TOOLTIP_OPTION, HEAD_LIST} from './js/contant.js'
import api from './api'
import {CONSTANT_OBJ} from '@/utils/constant'
import {copyText} from '@/utils/util'
import AddOrEditOrg from './components/AddOrEdit'
import {mapState} from 'vuex'

export default {
  components: {AddOrEditOrg},
  data () {
    return {
      TOOLTIP_OPTION,
      HEAD_LIST,
      tableLoading: false,
      dialog: {
        orgDialog: false,
        userDialog: false,
        setDialog: false
      },
      orgTree: [],
      orgTree1: [],
      orgTreeProps: {
        children: 'childOrganizations',
        label: 'organizationName',
        disabled: true
      },
      orgTreeProps1: {
        children: 'childOrganizations',
        label: 'organizationName',
        disabled: true
      },
      //当前选择的机构
      currentOrg: '',
      dialogTitle: '',
      editData: {},
      organizationId: '',
      orgData: {},
      orgForm: {
        parentOrganizationId: '',
        pageNum: 1,
        pageSize: 10
      },
      dataList: [],
      total: 0
    }
  },
  mounted () {
    this.getTree(true)
    this.getTree1(true)
  },
  methods: {
    // 查询树
    getTree (isFirst) {
      api.getQueryOrgTree().then(res => {
        const {responseCode, data} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.orgTree = data
          this.$store.commit('common/GET_ORG_TREE', data)
        }
      })
    },
    getTree1 (isFirst) {
      api.getQueryOrgTree1().then(res => {
        const {responseCode, data} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.orgTree1 = data
          if (this.currentOrg) {
            this.$nextTick(() => {
              if (data.length > 0) {
                this.$refs.orgTreeDom.setCurrentKey(this.currentOrg.organizationId)
                this.changeOrgNode(this.currentOrg)
              }
            })
          }
          if (isFirst) {
            this.$nextTick(() => {
              console.log('选择第一个节点', data)
              if (data.length > 0) {
                this.$refs.orgTreeDom.setCurrentKey(data[0].organizationId)
                this.currentOrg = data[0].organizationId
                this.changeOrgNode(data[0])
              }
            })
          }
        }
      })
    },
    // 选中渠道树节点
    changeOrgNode (data) {
      // if (data.childOrganizations && data.childOrganizations.length) {
        this.currentOrg = data
        this.orgForm.parentOrganizationId = data.organizationId
        this.getList(1)
      // }
    },
    // 查询列表
    getList (val) {
      this.orgForm.pageNum = val || this.orgForm.pageNum
      this.tableLoading = true
      api.postQueryOrgData(this.orgForm).then(res => {
        const {responseCode, data} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          let ver = Object.prototype.toString
          data.list.forEach(v => {
            v.newOrganizationStatus = this.dicts['organization_status'].childMap[v.organizationStatus] || v.organizationStatus
            v.newOrganizationType = this.dicts['organization_type'].childMap[v.organizationType] || v.organizationType
            if (ver.call(v.principal) === '[object Array]') {
              v.newPrincipal = v.principal.map(ele => {
                return `${ele.realName}(${ele.userName})`
              }).join(',')
            } else {
              v.newPrincipal = v.principal
            }
          })
          this.dataList = data.list || []
          this.total = parseInt(data.total) || 0
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    /**
     * @description 复制
     */
    copyRow (row) {
      const {orgName} = row
      copyText(orgName)
    },
    /**
     * @description 添加人员
     */
    addUser (row) {
      this.organizationId = row.organizationId
      this.dialog.userDialog = true
    },
    // 新增渠道
    addOrg () {
      this.editData = {}
      this.dialogTitle = '新增渠道'
      this.dialog.orgDialog = true
    },
    /**
     * @description 编辑
     */
    editRow (row) {
      this.dialogTitle = '编辑渠道'
      this.editData = {...row}
      this.dialog.orgDialog = true
    },
    // 添加子渠道
    addChildRow (row) {
      this.dialogTitle = '添加子渠道'
      this.editData = {
        parentOrganizationId: row.organizationId,
        organizationName: '',
        organizationCode: '',
        organizationType: row.organizationType,
        organizationStatus: 'OPEN',
        organizationDesc: '',
        principal: ''
      }
      this.dialog.orgDialog = true
    },
    // 删除渠道
    deleteRow (row) {
      console.log("22222222",row)
      if ((row.principal||'').length) {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: '<strong>渠道无法删除</strong><div>渠道有成员时无法删除</div>',
          type: 'error'
        })
      } else {
        this.$confirm(`<div style="padding-left: 50px"><strong style="font-size: 16px">删除渠道确认</strong><div>请确认是否删除 ${row.organizationName}（${row.organizationCode}） 渠道？</div></div>`, '确认提示', {
          dangerouslyUseHTMLString: true
        }).then(() => {
          api.deleteOrgData(row.organizationId).then(res => {
            this.successFn(res)
          })
        })
      }
    },
    // 停用更新数据
    uppdataOrg () {
      this.getList(1)
    },
    // 启用渠道
    openOrg (row) {
      this.$confirm('请确认是否启用渠道？', '确认提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.postOpenOrgData(row.organizationId).then(res => {
          this.successFn(res)
          const {responseCode} = res
          if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
            this.$store.dispatch('common/queryOrgTree')
          }
        })
      })
    },
    // 停用渠道
    closeOrg (row) {
      this.$confirm('请确认是否停用渠道？', '确认提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.postCloseOrgData(row.organizationId).then(res => {
          this.successFn(res)
          const {responseCode} = res
          if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
            this.$store.dispatch('common/queryOrgTree')
          }
        })
      })
    },
    updataData (data) {
      this.dialog[`${data}Dialog`] = false
      console.log("更新调用。。。。。。")
      this.getTree()
      this.getTree1()
      this.getList()
    },
    successFn (res) {
      const {responseCode, responseMsg: message} = res
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: 'success'
        })
        this.selectedIds = []
        this.getTree()
        this.getTree1()
        this.getList(1)
      }
    },
    closeEditOrg () {
      this.dialog.orgDialog = false
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
}
</script>
